const express = require('express');

const uid = require( '../utils/uid' );
const Book = require( '../models/book' );

const router = express.Router();

router.post( '/book/add' , (req,resp) => {
    let book = { id: uid.idGenerator() , ...req.body };
    // 根据用户提交过来的字符串创建一个Date实例
    book.pubDate = new Date( book.pubDate );
    // 使用 Book 模型中的 create 保存图书到数据库中
    Book.create( book ).then( p => {
        console.log('created.' + JSON.stringify(p));
        resp.json( { success: true , message: '保存成功' });
    } ).catch( err => {
        console.log('failed: ' + err);
        resp.json( { success: false , message: '保存失败' });
    } );
});

router.get( '/book/list' , async (req,resp) => {
    let array = await Book.findAll();
    resp.json( array );
});

router.get( '/book/remove/:id' , async (req,resp) => {
    let count = await Book.destroy( { where: { id: req.params.id } } );
    console.log( count );
    if( count > 0 ) {
        resp.json( { success: true , message: '删除成功' } );
        return ; //  使用 return 让方法立即结束
    } 
    resp.json( { success: false , message: '删除失败' } );
});

router.get( '/book/find/:id' , async (req,resp) => {
    let book = await Book.findByPk( req.params.id );
    if( book ) {
        // 使用 ES6 提供的展开运算符 将 book 中的属性展开到另外一个对象中
        resp.json( { success: true , message: '查询成功' , book: book } );
        return ; //  使用 return 让方法立即结束
    } 
    resp.json( { success: false , message: '查询失败' } );
});

router.post( '/book/update' , async (req,resp) => {
    let book = { ...req.body };
    console.log( book );
    let count = await Book.update( book , { where: { id: book.id } } );
    if( count == 1 ) {
        resp.json( { success: true , message: '修改成功' } );
        return ; 
    } 
    resp.json( { success: false , message: '修改失败' } );
});

module.exports = router ;